# This code is hosted on http://code.google.com/p/lenthorp/
# Freely available for use in applications, but should NOT be modified
# Email all comments to lenthorpresearch@gmail.com

import sys, os
import MySQLdb

if __name__ == "__main__":
    db = MySQLdb.connect("localhost",MySQLUsername,'',"regressionResults" )
    c = db.cursor()
    directories = []
    testTol = 1e-5
    try:
        print('... Starting regression testing ...')
        c.execute('SHOW TABLES')
        tables = c.fetchall()
        for table in tables:
            # assumes that all test scripts are stored in Projects\XXX\Test Scripts
            directories.append(mainLocation + 'Projects\\' + table[0] + '\\Test Scripts')

        for directory in directories:
            if not directory in sys.path:
                sys.path.append(directory)
 
        for table in tables:
            print('... Testing for ' + table[0] + ' ...')
            c.execute('SELECT ScriptName, Idx, Val FROM ' + table[0])
            data = c.fetchall()
            scriptValues = []
            for row in data:
                scriptValues.append(row[0])
            scriptValues = list(set(scriptValues)) # get the unique values    
            for script in scriptValues:
                print('... ... Testing for ' + script + ' ...')
                mod = __import__(script)
                c.execute('SELECT Idx, Val FROM ' + table[0] + ' WHERE ScriptName="' + script + '"')
                d = c.fetchall()
                res = mod.runTest()
                if not isinstance(res,list):
                    res = [res]
                for r in d:
                    if abs(res[int(r[0])] - float(r[1])) < testTol:
                        print('... ... ... pass')
                    else:
                        print('... ... ... fail')
        db.close()
    except:
        print('... ... Failed to run regression testing ...')
        raise Exception('Critical failure')
    
    